import { Editor } from './editor';

const operator = {
  setBold(context: Editor) {
    context.recoverRange();
    context.exec('bold');
  },
  setColor(context: Editor) {
    context.recoverRange();
    const color = prompt('请输入颜色') ?? '#000';
    context.exec('foreColor', false, color);
  },
  setBgColor(context: Editor) {
    context.recoverRange();
    const color = prompt('请输入颜色') ?? '#000';
    context.exec('backColor', true, color);
  }
};

/**
 * 创建编辑的DOM元素，并设置监听
 * @param target 目标元素
 * @param context 编辑器上下文
 */
export function createEditor(target: HTMLElement, context: Editor) {
  const editorEl = document.createElement('div');
  editorEl.className = 'simple-editor';
  const menubarEl = document.createElement('div');
  menubarEl.className = 'simple-editor-menubar';
  menubarEl.innerHTML = `
    <button>加粗</button>
    <button>颜色</button>
    <button>背景</button>
    <button>获取内容</button>
  `;
  menubarEl.addEventListener('click', (e: MouseEvent) => {
    const target = e.target as HTMLElement;
    switch (target.innerText) {
      case '加粗':
        operator.setBold(context);
        break;
      case '颜色':
        operator.setColor(context);
        break;
      case '背景':
        operator.setBgColor(context);
        break;
      case '获取内容':
        alert(contentEl.innerHTML);
        break;
    }
  });
  const contentEl = document.createElement('div');
  contentEl.className = 'simple-editor-content';
  contentEl.setAttribute('contenteditable', 'true');
  contentEl.addEventListener('blur', () => {
    context.setRange();
  });
  editorEl.appendChild(menubarEl);
  editorEl.appendChild(contentEl);
  target.appendChild(editorEl);
}
